package com.kungfuhacking.wristbandpro.my.presenter;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.kungfuhacking.wristbandpro.base.bean.Basebean;
import com.kungfuhacking.wristbandpro.base.bean.RequestBean;
import com.kungfuhacking.wristbandpro.base.presenter.BasePresenter;
import com.kungfuhacking.wristbandpro.base.presenter.PhotoPresenter;
import com.kungfuhacking.wristbandpro.login.activity.LoginActivity;
import com.kungfuhacking.wristbandpro.my.bean.OldDetail;
import com.kungfuhacking.wristbandpro.my.view.IOldDetailView;
import com.kungfuhacking.wristbandpro.net.BaseNoTObserver;
import com.kungfuhacking.wristbandpro.net.RetrofitHttpUtil;
import com.kungfuhacking.wristbandpro.utils.CommonUtils;
import com.kungfuhacking.wristbandpro.utils.Constant;

import io.reactivex.disposables.Disposable;

/**
 * Created by Aaron on 17/5/26.
 */

public class IOldDetailPresenter extends PhotoPresenter implements BasePresenter {

    private IOldDetailView iOldDetailView;
    private OldDetail mOldDetail = new OldDetail();

    public IOldDetailPresenter(IOldDetailView iOldDetailView) {
        this.iOldDetailView = iOldDetailView;
    }

    private boolean canModifyInfo = false; //是否可以修改老人信息 (管理员才有权限修改)

    public boolean isCanModifyInfo() {
        return canModifyInfo;
    }

    /**
     * 获取老人详细信息
     *
     * @param id
     */
    public void oldDetailInfo(String id) {

        JSONObject j = new JSONObject();
        j.put("id", id);
        j.put("token", iOldDetailView.getSp().getString(Constant.TOKEN, ""));

        RetrofitHttpUtil.getInstance().getChildInfo(new BaseNoTObserver<OldDetail>() {
            @Override
            public void onHandleSuccess(OldDetail oldDetail) {
                mOldDetail = oldDetail;
                iOldDetailView.setAdapterInfp(oldDetail);
//                int mylevel = oldDetail.getMylevel();
                canModifyInfo = Constant.POWER_ADMIN == oldDetail.getMylevel();
            }

            @Override
            public void onHandleError(String message) {
                iOldDetailView.showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                Log.e("IOldDetailPresenter", "异地登录，需要重新登录.");

                iOldDetailView.hideLoading();
                iOldDetailView.showErr(message);
                iOldDetailView.nextActivity(LoginActivity.class);
//                Bundle b = new Bundle();
//                b.putBoolean("autoLogin", false);
//                iOldDetailView.exitApp();
//                iOldDetailView.nextActivityWithBundle(LoginActivity.class, b);

//                ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//                manager.restartPackage(packageName);

            }

            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
            }

        }, new RequestBean().setData(j.toString()));

    }

    /**
     * 修改权限
     */
    public void modifyPermission(final String id, int level, String phoneNum) {

        JSONObject j = new JSONObject();
        j.put("id", id);//老人的id
        j.put("token", iOldDetailView.getToken());
        j.put("level", level);
        j.put("phoneNum", phoneNum);//被提示或者降级的用户id
//        j.put("userId", phoneNum);//被提示或者降级的用户id

        RetrofitHttpUtil.getInstance().updateLevel(new BaseNoTObserver<Basebean>() {
            @Override
            public void onHandleSuccess(Basebean basebean) {
                iOldDetailView.hideLoading();
                oldDetailInfo(id);
            }

            @Override
            public void onHandleError(String message) {
                iOldDetailView.showErr(message);
                iOldDetailView.hideLoading();
            }

            @Override
            public void onReLogin(String message) {
                iOldDetailView.hideLoading();
                iOldDetailView.showErr(message);
                iOldDetailView.nextActivityWithSingleTask(LoginActivity.class);
            }

            @Override
            public void onSubscribe(Disposable d) {

                iOldDetailView.showLoading("加载中...");
                compositeDisposable.add(d);
            }
        }, new RequestBean().setData(j.toString()));

    }

    /**
     * 裁剪图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        iOldDetailView.nextActivityForPhoto(intent, PHOTO_RESOULT);
    }

    /**
     * 获取七牛上传的token
     *
     * @param data
     * @param id
     */
    public void getToken(Intent data, final String id) {

        Bundle extras = data.getExtras();

        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");

            getUploadToken(CommonUtils.compressByte(photo), iOldDetailView, new OnResultListener() {
                @Override
                public void onSuccess(String imgUrl) {
                    //图片上传成功
                    if (mOldDetail.getData() != null)
                        updateOldInfo(id, imgUrl, mOldDetail.getData().getBirthDay()
                                , mOldDetail.getData().getChildName(), mOldDetail.getData().getSex());

                }
            });
        }

    }

    /**
     * 更新老人信息
     *
     * @param id       老人id
     * @param imageUrl 老人头像
     * @param birthday 老人生日
     */
    public void updateOldInfo(String id, final String imageUrl, final String birthday, final String name, final String sex) {

        JSONObject j = new JSONObject();
        j.put("id", id);
        j.put("token", iOldDetailView.getToken());
        j.put("photo", imageUrl);
        j.put("birthDay", birthday);
        j.put("name", name);
        j.put("sex", sex);

        RetrofitHttpUtil.getInstance().updateOldInfo(new BaseNoTObserver<Basebean>() {
            @Override
            public void onHandleSuccess(Basebean basebean) {
                //修改成功
                mOldDetail.getData().setPicUrl(imageUrl);
                mOldDetail.getData().setBirthDay(birthday);
                mOldDetail.getData().setChildName(name);
                mOldDetail.getData().setSex(sex);
                iOldDetailView.setUpdateInfo(imageUrl, birthday, name, sex);
            }

            @Override
            public void onHandleError(String message) {
                iOldDetailView.showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                iOldDetailView.hideLoading();
                iOldDetailView.showErr(message);
                iOldDetailView.nextActivityWithSingleTask(LoginActivity.class);
            }

            @Override
            public void onSubscribe(Disposable d) {

            }
        }, new RequestBean().setData(j.toString()));

    }


    /**
     * 删除老人
     *
     * @param oldId 老人的id
     */
    public void deleteOld(final String oldId) {

        JSONObject j = new JSONObject();
        j.put("id", oldId);
        j.put("token", iOldDetailView.getToken());

        RetrofitHttpUtil.getInstance().delOld(new BaseNoTObserver<Basebean>() {
            @Override
            public void onHandleSuccess(Basebean basebean) {
                iOldDetailView.hideLoading();
                iOldDetailView.showErr("删除成功");

//                //聊天数据库中删除老人的聊天列表
//                DatabaseManager.getInstance().deleteTopic(iOldDetailView.getContext(), );

                //判断当前选择的老人 是不是删除的老人，如果是则清空数据
                SharedPreferences sp = iOldDetailView.getSp();
                if (oldId.equals(sp.getString(Constant.CURRENTOLDID, ""))) {
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString(Constant.CURRENTOLDID, "");
                    edit.putString(Constant.CURRENTOLDNAME, "");
                    edit.apply();
                }
                iOldDetailView.finishPage();

            }

            @Override
            public void onHandleError(String message) {
                iOldDetailView.hideLoading();
                iOldDetailView.showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                iOldDetailView.hideLoading();
                iOldDetailView.showErr(message);
                iOldDetailView.nextActivityWithSingleTask(LoginActivity.class);
            }

            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
                iOldDetailView.showLoading("删除中...");
            }
        }, new RequestBean().setData(j.toString()));
    }


    @Override
    public void clearRequest() {
        compositeDisposable.clear();
    }
}
